package com.uls.ycl.service.impl;

import java.util.*;

import com.uls.common.core.domain.entity.SysUser;
import com.uls.system.service.ISysUserService;
import com.uls.system.service.impl.SysUserServiceImpl;
import com.uls.ycl.domain.RepairEvaluation;
import com.uls.ycl.domain.RepairPersonnel;
import com.uls.ycl.domain.RepairRecord;
import com.uls.ycl.mapper.RepairEvaluationMapper;
import com.uls.ycl.mapper.RepairPersonnelMapper;
import com.uls.ycl.mapper.RepairRecordMapper;
import com.uls.ycl.vo.TaskCommentVo;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uls.ycl.mapper.RepairRequestMapper;
import com.uls.ycl.domain.RepairRequest;
import com.uls.ycl.service.IRepairRequestService;
import org.springframework.transaction.annotation.Transactional;

import static com.uls.common.utils.SecurityUtils.getUserId;

/**
 * 报修请求Service业务层处理
 * 
 * @author ycl
 * @date 2024-11-06
 */
@Service
public class RepairRequestServiceImpl implements IRepairRequestService 
{
    @Autowired
    private RepairRequestMapper repairRequestMapper;



    @Autowired
    private RuntimeService runtimeService;


    @Autowired
    private TaskService taskService;


    @Autowired
    private ISysUserService userService;  //取用户名
    @Autowired
    private RepairPersonnelMapper repairPersonnelMapper;//取维修人员
    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepairEvaluationMapper repairEvaluationMapper;
    @Autowired
    private RepairRecordMapper repairRecordMapper;
    /**
     * 查询报修请求
     * 
     * @param requestId 报修请求主键
     * @return 报修请求
     */
    @Override
    public RepairRequest selectRepairRequestByRequestId(Long requestId)
    {
        return repairRequestMapper.selectRepairRequestByRequestId(requestId);
    }

    /**
     * 查询报修请求列表
     * 
     * @param repairRequest 报修请求
     * @return 报修请求
     */
    @Override
    public List<RepairRequest> selectRepairRequestList(RepairRequest repairRequest)
    {
        return repairRequestMapper.selectRepairRequestList(repairRequest);
    }

    /**
     * 新增报修请求
     * 
     * @param repairRequest 报修请求
     * @return 结果
     */
    @Override
    public int insertRepairRequest(RepairRequest repairRequest)
    {
        return repairRequestMapper.insertRepairRequest(repairRequest);
    }

    /**
     * 修改报修请求
     * 
     * @param repairRequest 报修请求
     * @return 结果
     */
    @Override
    public int updateRepairRequest(RepairRequest repairRequest)
    {
        return repairRequestMapper.updateRepairRequest(repairRequest);
    }

    /**
     * 批量删除报修请求
     * 
     * @param requestIds 需要删除的报修请求主键
     * @return 结果
     */
    @Override
    public int deleteRepairRequestByRequestIds(Long[] requestIds)
    {
        return repairRequestMapper.deleteRepairRequestByRequestIds(requestIds);
    }

    /**
     * 删除报修请求信息
     * 
     * @param requestId 报修请求主键
     * @return 结果
     */
    @Override
    public int deleteRepairRequestByRequestId(Long requestId)
    {
        return repairRequestMapper.deleteRepairRequestByRequestId(requestId);
    }



    /**
     * 启动流程
     *
     * @param
     * @param userId
     */
    @Override
    @Transactional
    public int submit(Long requestId, Long userId) {
        RepairRequest request = repairRequestMapper.selectRepairRequestByRequestId(requestId);

        String processDefiKey = "myrepair";
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("inputUser1", userId);
        variables.put("inputUser2", 1);  //先写死，是主任的编号
        //没有启动这个流程
        if (request.getStatus() == 7) {
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
            request.setFlowInstantId(Long.parseLong(pi.getProcessInstanceId()));  // 把流程实例id与业务系统绑定
            request.setStatus(2);//状态(7-未提交，1-打回，2-待处理，3-维修中，4.已完成，5-退单中，6-转单中）
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .taskAssignee("" + userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());

            return repairRequestMapper.updateRepairRequest(request);
        }
        //流程启动了，打回重新审批，就不用再启动流程
        else {

            Long flowInstantId = request.getFlowInstantId();
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowInstantId)
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());
            request.setStatus(2);//状态(7-未提交，1-打回，2-待处理，3-维修中，4.已完成，5-退单中，6-转单中）
            return repairRequestMapper.updateRepairRequest(request);
        }


    }


    //查询不带条件提交申请但未审批的学生信息
    @Override
    @Transactional
    public List<RepairRequest> noFinishTask(Long userId, String processDefiniionKey) {
        List<RepairRequest> listRequest = new ArrayList<RepairRequest>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee("" + userId)
                .processDefinitionKey(processDefiniionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("输入学生报修")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    //根据流程id查询学生mapper的方法
                    RepairRequest request = repairRequestMapper.selectRepairRequestFlowId(flowInstanceId);
                    listRequest.add(request);
                }

            }
        }

        return listRequest;
    }


    //带条件查询提交申请但未审批的学生信息
    @Override
    @Transactional
    public List<RepairRequest> noFinishTask(Long userId, String processDefiniionKey, RepairRequest request) {
        List<RepairRequest> listRequest = new ArrayList<RepairRequest>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee("" + userId)
                .processDefinitionKey(processDefiniionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("输入学生报修")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    request.setFlowInstantId(flowInstanceId);
                    //根据流程id和其他条件查询老师mapper的方法
                    RepairRequest request1 = repairRequestMapper.selectRepairRequestFlowIdOther(request);
                    if (request1 != null)
                        listRequest.add(request1);
                }

            }
        }

        return listRequest;
    }


    //审批
    @Override
    @Transactional
    public void completeTask(Long flowInstantId, Integer agree, Long userId, String comment, Long requestId) {

        RepairRequest request = repairRequestMapper.selectRepairRequestByRequestId(requestId);
        //获取当前报修单的报修人员id
        RepairPersonnel personnel = null;
        Long id = null;
        if(request.getPersonnelId()!=null) {
             personnel = repairPersonnelMapper.selectRepairPersonnelByPersonnelId(request.getPersonnelId());
             id = personnel.getUserId();
        }
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .processInstanceId("" + flowInstantId)
                .list();
        // 遍历任务列表
        Map<String, Object> params = new HashMap<String, Object>();

        if (list != null && list.size() > 0) {
            for (Task task : list) {

                if (task.getName().equals("后台审批")) {
                    if (agree == 1) {
                        if (id == null ) {
                            throw new IllegalArgumentException("请分派维修人员");
                        }
                        params.put("inputUser3", id);  //
                        request.setStatus(2);//状态(7-未提交，1-打回，2-待处理，3-维修中，4.已完成，5-退单中，6-转单中）
                    } else {
                        request.setStatus(1);
                    }
                    params.put("pass1", agree);  //给流程变量赋值

                } else if (task.getName().equals("维修人员")) {
                    if (agree == 1) {
                        params.put("inputUser4", id);  //固定一个人员4
                        request.setStatus(3);
                        //同时增加一条维修开始记录
                        RepairRecord repairRecord = new RepairRecord();
                        repairRecord.setRequestId(requestId);
                        repairRecord.setPersonnelId(request.getPersonnelId());
                        repairRecord.setStatus(3);
                        repairRecord.setStartTime(new Date());
                        repairRecordMapper.insertRepairRecord(repairRecord);

                    } else {
                        request.setStatus(5);
                        //同时增加一条维修退单记录
                       // request.setPersonnelId(null);
                        RepairRecord repairRecord = new RepairRecord();
                        repairRecord.setRequestId(requestId);
                        repairRecord.setPersonnelId(request.getPersonnelId());
                        repairRecord.setStatus(5);
                        repairRecord.setStartTime(new Date());
                        repairRecordMapper.insertRepairRecord(repairRecord);

                    }
                    params.put("pass2", agree);  //给流程变量赋值
                } else if (task.getName().equals("维修中")) {
                    if (agree == 1) {
                        request.setStatus(4);
                        //完成维修同时添加报修评价
                        RepairEvaluation repairEvaluation = new RepairEvaluation();
                        repairEvaluation.setRequestId(requestId);//报修单id
                        repairEvaluation.setUserId(request.getUserId());
                        repairEvaluation.setName(personnel.getName());//维修人员
                        repairEvaluationMapper.insertRepairEvaluation(repairEvaluation);
                        //同时增加一条维修结束记录
                        RepairRecord repairRecord = new RepairRecord();
                        repairRecord.setRequestId(requestId);
                        repairRecord.setPersonnelId(request.getPersonnelId());
                        repairRecord.setStatus(4);
                        repairRecord.setEndTime(new Date());
                        repairRecordMapper.insertRepairRecord(repairRecord);

                    } else {
                        request.setStatus(6);
                        //同时增加一条维修失败转单记录
                        RepairRecord repairRecord = new RepairRecord();
                        repairRecord.setRequestId(requestId);
                        repairRecord.setPersonnelId(request.getPersonnelId());
                        repairRecord.setStatus(6);
                        repairRecord.setStartTime(new Date());
                        repairRecordMapper.insertRepairRecord(repairRecord);

                    }
                    params.put("pass3", agree);  //给流程变量赋值
                }


                repairRequestMapper.updateRepairRequest(request);

                // 添加批注时候的审核人，通常应该从session获取,现在从redis
                Authentication.setAuthenticatedUserId(userId.toString());

                if (comment == null) {
                    comment = ""; // 设置默认评论
                }
                // 添加批注
                taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
                // taskId：任务id
                taskService.complete(task.getId(), params);


            }
        }

    }

    //查询审批历史
    @Override
    public List<TaskCommentVo> getTaskCommentList(Long flowInstantId) {

        List<TaskCommentVo> taskCommentVoList = new ArrayList<>();

        List<Comment> list = new ArrayList();

        //从历史批注中取数据
        list = taskService.getProcessInstanceComments("" + flowInstantId);

        for (Comment com : list) {
            TaskCommentVo taskCommentVo = new TaskCommentVo();
            taskCommentVo.setMessage(com.getFullMessage());

            SysUser user = userService.selectUserById(Long.parseLong(com.getUserId()));  //查询用户名

            taskCommentVo.setUserName(user.getUserName());


            //从历史任务取数据
            List<HistoricTaskInstance> hist = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId("" + flowInstantId)
                    .taskId(com.getTaskId())
                    .list();
            if (hist != null && hist.size() > 0) {
                HistoricTaskInstance historicTaskInstance = hist.get(0);
                taskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                taskCommentVo.setTaskName(historicTaskInstance.getName());

                taskCommentVo.setEndtime(historicTaskInstance.getEndTime());

            }

            taskCommentVoList.add(taskCommentVo);

        }


        //排序
        List<TaskCommentVo> taskCommentVoListSort = new ArrayList<>();

        for (int i = taskCommentVoList.size() - 1; i >= 0; i--) {
            TaskCommentVo temp = taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);
        }

        return taskCommentVoListSort;
    }

    //已完成的任务
    @Override
    public List<RepairRequest> finishedTask(Long userId, String processDefiniionKey, RepairRequest request) {
        List<RepairRequest> listFinishedReuqest = new ArrayList<RepairRequest>();
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processDefinitionKey(processDefiniionKey)
                .processFinished()
                .list();
        if (list != null && list.size() > 0) {
            for (HistoricTaskInstance hti : list) {
                if (!hti.getName().equals("输入学生报修")) {
                    Long flowInstanceId = Long.parseLong(hti.getProcessInstanceId());
                    request.setFlowInstantId(flowInstanceId);
                    RepairRequest request1=repairRequestMapper.selectRepairRequestFlowIdOther(request);
                    if (request1!=null)
                        listFinishedReuqest.add(request1);
                }


            }
        }
        //去重
        List<RepairRequest> listFinishedReuqest1 = new ArrayList<>(new HashSet<>(listFinishedReuqest));
        return listFinishedReuqest1;
    }



}
